﻿/***********************************************************************************************
 * 
 * ProjectName: WMSSoft.Lib.WinKStart
 * 
 * Description: ViewModel for Dialog Settings_NewEditContextMenuTarget
 * 
 * Created:     19.08.2015
 * 
 * Author:      matthias wagler - matthias@WMSSoft.de
 * 
 * Copyright:   Copyright 2015 by WMSSoft.net
 * 
 * License:     GPLv3
 * 
 * History:     19.08.2015 - matthias wagler matthias@WMSSoft.de   -   Created
 * 
 **********************************************************************************************/
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using WMSSoft.Lib.Basic;
using WMSSoft.Lib.Enums;
using WMSSoft.Lib.WinKStart;
using WMSSoft.Lib.Texte;
using WMSSoft.Lib.WinKStart.Model;
using WMSSoft.Lib.WinKStart.ViewModel;
using WMSSoft.Lib.WinKStart.Extension;
using WMSSoft.Lib.WinKStart.Abstract;
using WMSSoft.Lib.WinKStart.Model.MenuConfig;
using WMSSoft.Lib.WinKStart.Classes.Metadata;
using System.Reflection;

namespace WMSSoft.WinKStart.ViewModel
{
    public class Settings_NewEditContextMenuTargetViewModel : SettingBaseListViewModel
    {
        CContextMenuTargetItem _Data = null;
        CContentConfig _ContentConfig = null;
        List<KeyValueAssignment> _UsedRegionCaptions = null;
        List<cWinKStartContextMenuItem> _CustomMenuItems;
        List<KeyValueAssignment> _TargetTypes = null;
        List<string> _UsedIn = null;
        cWinKStartContextMenuItem _SelectedMenuItem = null;
        KeyValueAssignment _SelectedUsedIn = null;
        string _ContextTargetName = "";
        bool _DataChanged = false;
        bool _CanDeleteItem = false;
        bool _CanEditDeleteUsedIn = false;
        int _NextMenuId = 500;
        string _ContextTargetType = "";

        public event EventHandler DataChanged;

        #region Initialize

        public Settings_NewEditContextMenuTargetViewModel(CContentConfig ContentConfig)
        {
            try
            {
                base.ViewName = LanguageStrings.GetText("New Context Menu Target");
                PropertyChanged += Settings_NewEditContextMenuTargetViewModel_PropertyChanged;

                _ContentConfig = ContentConfig;

                _Data = new CContextMenuTargetItem();
                UsedIn = new List<KeyValueAssignment>();
                CustomMenuItems = new List<cWinKStartContextMenuItem>();
                _TargetTypes = Meta_ContextMenu.GetTargeteTypes();

                ViewModel_AddClick += Settings_NewEditContextMenuTargetViewModel_ViewModel_AddClick;
                ViewModel_EditClick += Settings_NewEditContextMenuTargetViewModel_ViewModel_EditClick;
                ViewModel_DeleteClick += Settings_NewEditContextMenuTargetViewModel_ViewModel_DeleteClick;

                ViewModel_ApplyClick += Settings_NewEditContextMenuTargetViewModel_ViewModel_ApplyClick;
                ViewModel_OkClick += Settings_NewEditContextMenuTargetViewModel_ViewModel_OkClick;
                ViewModel_CloseClick += Settings_NewEditContextMenuTargetViewModel_ViewModel_CloseClick;

                m_oCommands.Add(new CSingleCommandViewModel(LanguageStrings.GetText("Add"), new CDelegatingCommand(Delegate => this.Cmd_Exec_AddUsedInClick())));
                m_oCommands.Add(new CSingleCommandViewModel(LanguageStrings.GetText("Delete"), new CDelegatingCommand(Delegate => this.Cmd_Exec_DeleteUsedInClick())));

                _DataChanged = false;
            }
            catch (Exception Ex)
            {
                throw new Exception("Unable to Initialize Dialog!", Ex);
            }
        }

        public Settings_NewEditContextMenuTargetViewModel(CContextMenuTargetItem Data, CContentConfig ContentConfig)
        {
            try
            {
                base.ViewName = LanguageStrings.GetText("Edit Context Menu Target");

                PropertyChanged += Settings_NewEditContextMenuTargetViewModel_PropertyChanged;

                _ContentConfig = ContentConfig;

                _Data = Data;

                Name = Data.Name;
                Type = Data.TargetType.ToString();
                //UsedIn = _Data.UsedIn;
                UsedIn = new List<KeyValueAssignment>();
                ApplyUsedRegionsToUsedRegionCaptions();
                CustomMenuItems = _Data.CustomMenuItems;

                _TargetTypes = Meta_ContextMenu.GetTargeteTypes();

                ViewModel_AddClick += Settings_NewEditContextMenuTargetViewModel_ViewModel_AddClick;
                ViewModel_EditClick += Settings_NewEditContextMenuTargetViewModel_ViewModel_EditClick;
                ViewModel_DeleteClick += Settings_NewEditContextMenuTargetViewModel_ViewModel_DeleteClick;

                ViewModel_ApplyClick += Settings_NewEditContextMenuTargetViewModel_ViewModel_ApplyClick;
                ViewModel_OkClick += Settings_NewEditContextMenuTargetViewModel_ViewModel_OkClick;
                ViewModel_CloseClick += Settings_NewEditContextMenuTargetViewModel_ViewModel_CloseClick;

                m_oCommands.Add(new CSingleCommandViewModel(LanguageStrings.GetText("Add"), new CDelegatingCommand(Delegate => this.Cmd_Exec_AddUsedInClick())));
                m_oCommands.Add(new CSingleCommandViewModel(LanguageStrings.GetText("Delete"), new CDelegatingCommand(Delegate => this.Cmd_Exec_DeleteUsedInClick())));

                _DataChanged = false;
            }
            catch (Exception Ex)
            {
                throw new Exception("Unable to Initialize Dialog!", Ex);
            }
        }

        #endregion

        #region Properties

        public CSingleCommandViewModel Cmd_AddUsedInClick
        {
            get { return m_oCommands[6]; }
        }

        public CSingleCommandViewModel Cmd_DeleteUsedInClick
        {
            get { return m_oCommands[7]; }
        }

        public List<KeyValueAssignment> TargetTypes
        {
            get { return _TargetTypes; }
            set
            {
                _TargetTypes = value;
                OnPropertyChanged("TargetTypes");
            }
        }

        public CContextMenuTargetItem Data
        {
            get { return _Data; }
            set
            {
                _Data = value;
                OnPropertyChanged("Data");
            }
        }

        public string Name
        {
            get { return _ContextTargetName; }
            set
            {
                _ContextTargetName = value;
                OnPropertyChanged("Name");
            }
        }

        public string Type
        {
            get { return _ContextTargetType; }
            set
            {
                _ContextTargetType = value;
                OnPropertyChanged("Type");
            }
        }

        public List<KeyValueAssignment> UsedIn
        {
            get { return _UsedRegionCaptions; }
            set
            {
                _UsedRegionCaptions = value;
                OnPropertyChanged("UsedIn");
            }
        }

        public List<cWinKStartContextMenuItem> CustomMenuItems
        {
            get { return _CustomMenuItems; }
            set
            {
                _CustomMenuItems = value;
                OnPropertyChanged("CustomMenuItems");
            }
        }

        public cWinKStartContextMenuItem SelectedMenuItem
        {
            get { return _SelectedMenuItem; }
            set
            {
                _SelectedMenuItem = value;
                OnPropertyChanged("SelectedMenuItem");
            }
        }

        public KeyValueAssignment SelectedUsedIn
        {
            get { return _SelectedUsedIn; }
            set
            {
                _SelectedUsedIn = value;
                OnPropertyChanged("SelectedUsedIn");
            }
        }

        public bool CanDeleteItem
        {
            get { return _CanDeleteItem; }
            set
            {
                _CanDeleteItem = value;
                OnPropertyChanged("CanDeleteItem");
            }
        }

        public bool CanEditDeleteUsedIn
        {
            get { return _CanEditDeleteUsedIn; }
            set
            {
                _CanEditDeleteUsedIn = value;
                OnPropertyChanged("CanEditDeleteUsedIn");
            }
        }

        #endregion

        void Settings_NewEditContextMenuTargetViewModel_PropertyChanged(object sender, System.ComponentModel.PropertyChangedEventArgs e)
        {
            _DataChanged = true;
            if (e.PropertyName == "SelectedMenuItem")
            {
                if (SelectedMenuItem != null)
                    CanDeleteItem = true;
                else
                    CanDeleteItem = false;
            }
            else if (e.PropertyName == "SelectedUsedIn")
            {
                if (SelectedUsedIn != null)
                    CanEditDeleteUsedIn = true;
                else
                    CanEditDeleteUsedIn = false;
            }
        }

        #region Command-Procedures

        void Settings_NewEditContextMenuTargetViewModel_ViewModel_DeleteClick(object sender, EventArgs e)
        {
            try
            {
                System.Windows.Controls.ListView tmpListView = null;
                if ((System.Windows.Controls.ListView)((CDelegatingCommand)Cmd_DeleteClick.Command).CommandParameter != null)
                {
                    tmpListView = (System.Windows.Controls.ListView)((CDelegatingCommand)Cmd_DeleteClick.Command).CommandParameter;
                    if (_SelectedMenuItem != null)
                    {
                        string sCaption = ((cWinKStartContextMenuItem)_SelectedMenuItem).Caption;
                        if (System.Windows.MessageBox.Show(LanguageStrings.GetText("Delete selected Context-Menu-Item?"),
                            LanguageStrings.GetText("Question"),
                            System.Windows.MessageBoxButton.YesNo) == System.Windows.MessageBoxResult.Yes)
                        {
                            Data.CustomMenuItems.Remove((cWinKStartContextMenuItem)_SelectedMenuItem);
                            if (tmpListView != null) tmpListView.Items.Refresh();
                        }
                    }
                }
            }
            catch (Exception Ex)
            {
                CMessagelogging.AppendMessage("Can't delete selected Context-Menu - Item!", Ex, EMessageTypes.Error);
            }
        }

        void Settings_NewEditContextMenuTargetViewModel_ViewModel_EditClick(object sender, EventArgs e)
        {
            try
            {
                System.Windows.Controls.ListView tmpListView = null;
                if ((System.Windows.Controls.ListView)((CDelegatingCommand)Cmd_EditClick.Command).CommandParameter != null)
                {
                    tmpListView = (System.Windows.Controls.ListView)((CDelegatingCommand)Cmd_EditClick.Command).CommandParameter;
                    if (_SelectedMenuItem != null)
                    {
                        Settings_NewContextMenuItemViewModel tmpViewModel = new Settings_NewContextMenuItemViewModel((cWinKStartContextMenuItem)_SelectedMenuItem, _ContentConfig.Regions);                        
                        Settings_NewContextMenuItem oNewContextDlg = new Settings_NewContextMenuItem();                        
                        oNewContextDlg.DataContext = tmpViewModel;
                        if (oNewContextDlg.ShowDialog() == true)
                        {
                            _SelectedMenuItem = (cWinKStartContextMenuItem)oNewContextDlg.DataContext;
                            if (tmpListView != null) tmpListView.Items.Refresh();
                        }

                    }
                }
            }
            catch (Exception Ex)
            {
                CMessagelogging.AppendMessage("Can't create new Context-Menu - Item!", Ex, EMessageTypes.Error);
            }
        }

        void Settings_NewEditContextMenuTargetViewModel_ViewModel_AddClick(object sender, EventArgs e)
        {
            try
            {
                System.Windows.Controls.ListView tmpListView = null;
                if ((System.Windows.Controls.ListView)((CDelegatingCommand)Cmd_AddClick.Command).CommandParameter != null)
                {
                    tmpListView = (System.Windows.Controls.ListView)((CDelegatingCommand)Cmd_AddClick.Command).CommandParameter;

                    Settings_NewContextMenuItemViewModel tmpViewModel = new Settings_NewContextMenuItemViewModel(_ContentConfig.Regions);                              

                    Settings_NewContextMenuItem oNewContextDlg = new Settings_NewContextMenuItem();
                    oNewContextDlg.DataContext = tmpViewModel;
                    if (oNewContextDlg.ShowDialog() == true)
                    {
                        //add new context-menu item to list
                        //TODO: add the ContextMenuId before add it to List
                        ((Settings_NewContextMenuItemViewModel)oNewContextDlg.DataContext).Data.MenuID = _NextMenuId;
                        _NextMenuId++;
                        Data.CustomMenuItems.Add(((Settings_NewContextMenuItemViewModel)oNewContextDlg.DataContext).Data);
                        if (tmpListView != null) tmpListView.Items.Refresh();

                    }
                }
            }
            catch (Exception Ex)
            {
                CMessagelogging.AppendMessage("Can't create new Context-Menu - Item!", Ex, EMessageTypes.Error);
            }
        }

        void Settings_NewEditContextMenuTargetViewModel_ViewModel_CloseClick(object sender, EventArgs e)
        {
            try
            {
                Settings_NewEditContextMenuTarget parentDlg = null;
                if ((Settings_NewEditContextMenuTarget)((CDelegatingCommand)Cmd_CloseClick.Command).CommandParameter != null)
                {
                    parentDlg = (Settings_NewEditContextMenuTarget)((CDelegatingCommand)Cmd_CloseClick.Command).CommandParameter;

                    if (_DataChanged == true)
                    {
                        if (System.Windows.MessageBox.Show(QuestionMessages.QUESTION_CLOSE_DIALOG__LOSE_CHANGES, "Question",
                            System.Windows.MessageBoxButton.YesNo) == System.Windows.MessageBoxResult.No)
                            return;
                    }

                    if (parentDlg != null)
                        parentDlg.Close();

                }
            }
            catch (Exception Ex)
            {
                CMessagelogging.AppendMessage(LanguageStrings.GetText("Can't Close Dialog!"), Ex, EMessageTypes.Error);
            } 
        }

        void Settings_NewEditContextMenuTargetViewModel_ViewModel_OkClick(object sender, EventArgs e)
        {
            try
            {
                Settings_NewEditContextMenuTarget parentDlg = null;
                if ((Settings_NewEditContextMenuTarget)((CDelegatingCommand)Cmd_OkClick.Command).CommandParameter != null)
                {
                    parentDlg = (Settings_NewEditContextMenuTarget)((CDelegatingCommand)Cmd_OkClick.Command).CommandParameter;

                    if (ValidateAndApplyInputs() == true && parentDlg != null)
                        parentDlg.DialogResult = true;
                        parentDlg.Close();

                }
            }
            catch (Exception Ex)
            {
                CMessagelogging.AppendMessage(LanguageStrings.GetText("Can't Close Dialog!"), Ex, EMessageTypes.Error);
            } 
        }

        void Settings_NewEditContextMenuTargetViewModel_ViewModel_ApplyClick(object sender, EventArgs e)
        {
            try
            {
                if (ValidateAndApplyInputs() == true) if (DataChanged != null) DataChanged(this, EventArgs.Empty);
                _DataChanged = false;
            }
            catch (Exception Ex)
            {
                CMessagelogging.AppendMessage(LanguageStrings.GetText("Can't apply changes!"), Ex, EMessageTypes.Error);
            } 
        }

        void Cmd_Exec_AddUsedInClick()
        {
            try
            {
                System.Windows.Controls.ListBox tmpListBox = null;
                if ((System.Windows.Controls.ListBox)((CDelegatingCommand)Cmd_AddUsedInClick.Command).CommandParameter != null)
                {
                    tmpListBox = (System.Windows.Controls.ListBox)((CDelegatingCommand)Cmd_AddUsedInClick.Command).CommandParameter;

                    Setting_SelectRegionViewModel tmpViewModel = new Setting_SelectRegionViewModel(_ContentConfig.Regions);

                    Settings_SelectRegion SelRegionDlg = new Settings_SelectRegion();
                    SelRegionDlg.DataContext = tmpViewModel;
                    if (SelRegionDlg.ShowDialog() == true)
                    {
                        string selection = ((Setting_SelectRegionViewModel)SelRegionDlg.DataContext).SelectedRegion;

                        if (ContainsItem(selection) == false)
                        {
                            KeyValueAssignment NewItem = new KeyValueAssignment(selection, GetCaptionFromKey(selection));
                            _UsedRegionCaptions.Add(NewItem);
                            tmpListBox.Items.Refresh();
                        }
                    }
                }
            }
            catch (Exception Ex)
            {
                CMessagelogging.AppendMessage(ErrorMessages.USERSETTINGS__ERROR_UNABLE_TO_ADD_USED_CONTEXTMENU_REGION, Ex, EMessageTypes.Error);
            }
        }

        void Cmd_Exec_DeleteUsedInClick()
        {
            try
            {
                System.Windows.Controls.ListBox tmpListBox = null;
                if ((System.Windows.Controls.ListBox)((CDelegatingCommand)Cmd_DeleteUsedInClick.Command).CommandParameter != null)
                {
                    tmpListBox = (System.Windows.Controls.ListBox)((CDelegatingCommand)Cmd_DeleteUsedInClick.Command).CommandParameter;

                    //_SelectedItem

                    if (SelectedUsedIn != null && ContainsItem(SelectedUsedIn.Key) == true)
                    {
                        CanDeleteItem = false;
                        int itmpIndex = GetIndexFromKey(SelectedUsedIn.Key);
                        if (itmpIndex > -1)
                        {
                            if (System.Windows.MessageBox.Show(LanguageStrings.GetText("Delete selected Region?"),
                            LanguageStrings.GetText("Question"),
                            System.Windows.MessageBoxButton.YesNo) == System.Windows.MessageBoxResult.Yes)
                            {
                                _UsedRegionCaptions.RemoveAt(itmpIndex);
                                //OnPropertyChanged("RegionsListCaptions");
                                tmpListBox.Items.Refresh();
                            }
                        }
                    }
                }
            }
            catch (Exception Ex)
            {
                CMessagelogging.AppendMessage(ErrorMessages.USERSETTINGS__ERROR_UNABLE_TO_DELETE_USED_CONTEXTMENU_REGION, Ex, true, EMessageTypes.Error);
            }

        }

        #endregion

        #region Helper Methods

        /// <summary>
        /// Validate and apply Input Data
        /// </summary>
        /// <returns></returns>
        bool ValidateAndApplyInputs()
        {
            try
            {
                if (Data != null)
                {
                    if (_ContextTargetName.Length > 0)
                        Data.Name = _ContextTargetName;
                    else
                    {
                        System.Windows.MessageBox.Show(LanguageStrings.GetText(InfoMessages.INFO_NEW_EDIT_CONTEXT_MENU_TARGET__INVALID_NAME, EStringTypes.stMessage),
                                                       LanguageStrings.GetText("Info"), System.Windows.MessageBoxButton.OK);
                        return false;
                    }

                    if (_ContextTargetType.Length > 0)
                        Data.TargetType = (eContextMenuTarget)Enum.Parse(typeof(eContextMenuTarget), _ContextTargetType);
                    else
                    {
                        System.Windows.MessageBox.Show(LanguageStrings.GetText(InfoMessages.INFO_NEW_EDIT_CONTEXT_MENU_TARGET__INVALID_TYPE, EStringTypes.stMessage),
                                                       LanguageStrings.GetText("Info"), System.Windows.MessageBoxButton.OK);
                        return false;
                    }

                    if (_UsedRegionCaptions.Count > 0)
                    {
                        _Data.UsedIn.Clear();
                        //Apply DataChanges from ChildUse to Object
                        foreach (KeyValueAssignment Item in _UsedRegionCaptions)
                        {
                            _Data.UsedIn.Add(Item.Key);
                        }
                    }
                    else
                    {
                        System.Windows.MessageBox.Show(LanguageStrings.GetText(InfoMessages.INFO_NEW_EDIT_CONTEXT_MENU_TARGET__INVALID_NOT_ENOUGHT_USEDIN, EStringTypes.stMessage),
                                                       LanguageStrings.GetText("Info"), System.Windows.MessageBoxButton.OK);
                        return false;
                    }

                    if (Data.TargetType == eContextMenuTarget.SelectedItem | (CustomMenuItems.Count > 0 && Data.TargetType == eContextMenuTarget.Custom))
                    {
                        Data.CustomMenuItems = CustomMenuItems;
                    }
                    else
                    {
                        System.Windows.MessageBox.Show(LanguageStrings.GetText(InfoMessages.INFO_NEW_EDIT_CONTEXT_MENU_TARGET__INVALID_NOT_ENOUGHT_CUSTOMITEMS, EStringTypes.stMessage),
                                                       LanguageStrings.GetText("Info"), System.Windows.MessageBoxButton.OK);
                        return false;
                    }

                    return true;
                }
                else return false;
            }
            catch (Exception Ex)
            {
                throw new Exception("Can't apply Context-Menu - Target-Item - Data", Ex);
            }
        }

        bool ContainsItem(string Name)
        {
            try
            {
                foreach (KeyValueAssignment Item in _UsedRegionCaptions)
                {
                    if (Item.Key == Name)
                        return true;
                }
                return false;
            }
            catch
            {
                return false;
            }
        }

        string GetCaptionFromKey(string Key)
        {
            if (cMenuConfigReader.TabPages.ContainsKey(Key))
            {
                return LanguageStrings.GetText(cMenuConfigReader.TabPages[Key].Caption);
            }
            else
                return "";
        }

        int GetIndexFromKey(string Key)
        {
            for (int iCounter = 0; iCounter < _UsedRegionCaptions.Count; iCounter++)
            {
                if (_UsedRegionCaptions[iCounter].Key == Key)
                {
                    return iCounter;
                }
            }
            return -1;
        }

        void ApplyUsedRegionsToUsedRegionCaptions()
        {
            try
            {
                if (_Data != null && _Data.UsedIn != null && _Data.UsedIn.Count > 0)
                {
                    foreach (string Item in _Data.UsedIn)
                    {
                        if (cMenuConfigReader.TabPages.ContainsKey(Item) == true)
                        {
                            KeyValueAssignment tmpValue = new KeyValueAssignment(Item, LanguageStrings.GetText(cMenuConfigReader.TabPages[Item].Caption));
                            _UsedRegionCaptions.Add(tmpValue);
                        }
                    }
                }
            }
            catch (Exception Ex)
            {

            }

        }

        #endregion
    }
}
